package org.NooLab.itexx.storage;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;

import com.iciql.Db;

public class DataBaseMaintenance {

	// for call back of routines that need local info
	private ConnectorClientIntf connectorClient;
	
	PrintLog out = new PrintLog(2,false);
	DFutils fileutil = new DFutils();
	
	// ========================================================================
	public DataBaseMaintenance(ConnectorClientIntf cc){
		connectorClient = cc ;
	}
	// ========================================================================
	
	public void createDbUsers(ArrayList<DataBaseCreateCommand> ccs, Connection c) throws Exception {
		
		ArrayList<DbUser> users ;
		DbUser dbu;
		
		String str="";
		if (c.isClosed()){
			connectorClient.open(c);
		}

		
		try{
			DbUser.createDbUser(c, "sa", "sa") ;
		}catch(Exception e){
		}
		
		for (int i=0;i<ccs.size();i++){
			if (ccs.get(i).getDomain().toLowerCase().contentEquals("users")){
				users = ccs.get(i).getUsers();
				for(int u=0;u<users.size();u++){
					dbu = users.get(u); ;
					try{
						DbUser.createDbUser(c, dbu.getUsername(), dbu.getPassword()) ;
					}catch(Exception e){
						out.printErr(1, e.getMessage() + " ...while ettempting to create user <"+ dbu.getUsername()+">.") ;
					}
				}
				break;
			}
		}
		
		
	}
	
	
	public void disconnect(Connection connection){
		
		try{
			
			if (connection != null){
				
				if (connection.isClosed()==false){
					connection.commit();
					
					out.delay(100);
					
					connection.close(); 
				}
				
				out.delay(100);
				if (connection.isClosed()){
					connection = null;
				}
			}
			
		}catch( SQLException sx){
			sx.printStackTrace();
		}finally {
	         
	    }
		
	}



	public boolean removeLock( Connection connection, String storageDir){
		boolean rB=false;
		
		try{
		

			if (connection==null){
				ArrayList<String> locks = fileutil.listOfFiles("lock",".db", storageDir);
				for (int i=0;i<locks.size();i++){
					String fname = locks.get(i);
					if (DFutils.fileExists( fname)){
						fileutil.deleteFile( fname) ;
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return rB;
	}

	
	
	public PrintLog getOut() {
		return out;
	}

	public Db iciOpenTolerant(String databaseUrl, String user, String password){
		Db iciDb=null ;
		
		try{
			
				int z=0;
				while ((iciDb==null) && (z<5)){
			
					try{
						iciDb = Db.open(databaseUrl, user, password);
						
					}catch(Exception e){
						z++;
						PrintLog.Delay(100);
					}		
					
				}// ->
				
			
		}catch(Exception e){
			
		}
		
		return iciDb;
	}
	
}
